<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据源名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入数据源名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据源类型">
                <el-input :value="'Excel文件'" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入数据源描述"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>

        <!-- 文件配置 -->
        <el-tab-pane label="文件配置" name="fileConfig">
          <el-form-item label="文件来源" prop="fileConfig.sourceType">
            <el-radio-group v-model="formData.fileConfig.sourceType" @change="handleSourceTypeChange">
              <el-radio label="upload">本地上传</el-radio>
              <el-radio label="path">服务器路径</el-radio>
              <el-radio label="ftp">FTP服务器</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 本地上传配置 -->
          <template v-if="formData.fileConfig.sourceType === 'upload'">
            <el-form-item label="上传文件" prop="fileConfig.uploadFile">
              <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :limit="1"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                :file-list="fileList"
              >
                <el-button type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">请上传Excel文件（.xlsx, .xls）</div>
                </template>
              </el-upload>
            </el-form-item>
          </template>

          <!-- 服务器路径配置 -->
          <template v-else-if="formData.fileConfig.sourceType === 'path'">
            <el-form-item label="文件路径" prop="fileConfig.filePath">
              <el-input
                v-model="formData.fileConfig.filePath"
                placeholder="请输入服务器上的Excel文件路径"
              >
                <template #append>
                  <el-button @click="browseServerPath">浏览</el-button>
                </template>
              </el-input>
            </el-form-item>
          </template>

          <!-- FTP配置 -->
          <template v-else>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="FTP地址" prop="fileConfig.ftp.host">
                  <el-input v-model="formData.fileConfig.ftp.host" placeholder="请输入FTP服务器地址" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="端口" prop="fileConfig.ftp.port">
                  <el-input-number
                    v-model="formData.fileConfig.ftp.port"
                    :min="1"
                    :max="65535"
                    controls-position="right"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="fileConfig.ftp.username">
                  <el-input v-model="formData.fileConfig.ftp.username" placeholder="请输入FTP用户名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="密码" prop="fileConfig.ftp.password">
                  <el-input
                    v-model="formData.fileConfig.ftp.password"
                    type="password"
                    placeholder="请输入FTP密码"
                    show-password
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="文件路径" prop="fileConfig.ftp.filePath">
              <el-input
                v-model="formData.fileConfig.ftp.filePath"
                placeholder="请输入FTP服务器上的Excel文件路径"
              />
            </el-form-item>
          </template>

          <el-form-item label="文件预览" v-if="previewData.length > 0">
            <el-table
              :data="previewData"
              border
              height="300"
              style="width: 100%"
            >
              <el-table-column
                v-for="col in previewColumns"
                :key="col"
                :prop="col"
                :label="col"
              />
            </el-table>
          </el-form-item>
        </el-tab-pane>

        <!-- 工作表配置 -->
        <el-tab-pane label="工作表配置" name="sheetConfig">
          <el-form-item label="工作表选择" prop="sheetConfig.sheetName">
            <el-select
              v-model="formData.sheetConfig.sheetName"
              placeholder="请选择工作表"
              style="width: 100%"
              @change="handleSheetChange"
            >
              <el-option
                v-for="sheet in sheetList"
                :key="sheet"
                :label="sheet"
                :value="sheet"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="数据起始行" prop="sheetConfig.startRow">
            <el-input-number
              v-model="formData.sheetConfig.startRow"
              :min="1"
              controls-position="right"
              style="width: 100%"
            />
            <span class="el-form-item__tip">从第几行开始读取数据（包含表头）</span>
          </el-form-item>

          <el-form-item label="列标题行" prop="sheetConfig.headerRow">
            <el-input-number
              v-model="formData.sheetConfig.headerRow"
              :min="0"
              :max="formData.sheetConfig.startRow - 1"
              controls-position="right"
              style="width: 100%"
            />
            <span class="el-form-item__tip">设置为0表示没有标题行</span>
          </el-form-item>

          <el-form-item label="列映射配置">
            <el-button
              type="primary"
              size="small"
              @click="autoMapColumns"
              style="margin-bottom: 10px"
            >
              自动映射
            </el-button>
            <el-table
              :data="formData.sheetConfig.columnMappings"
              border
              style="width: 100%"
              empty-text="请先选择工作表并设置标题行"
            >
              <el-table-column prop="excelColumn" label="Excel列名" width="200">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.excelColumn"
                    placeholder="例如: A 或 姓名"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="targetField" label="目标字段">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.targetField"
                    placeholder="例如: name"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="dataType" label="数据类型" width="150">
                <template #default="{ row, $index }">
                  <el-select
                    v-model="row.dataType"
                    placeholder="选择数据类型"
                    style="width: 100%"
                  >
                    <el-option label="字符串" value="string" />
                    <el-option label="数字" value="number" />
                    <el-option label="日期" value="date" />
                    <el-option label="布尔值" value="boolean" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeColumnMapping($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item label="数据过滤" prop="sheetConfig.filterCondition">
            <el-input
              v-model="formData.sheetConfig.filterCondition"
              type="textarea"
              :rows="3"
              placeholder="输入过滤条件，例如: 年龄 > 18 AND 性别 = '男'"
            />
            <span class="el-form-item__tip">可选，用于过滤Excel中的数据</span>
          </el-form-item>
        </el-tab-pane>

        <!-- 采集调度 -->
        <el-tab-pane label="采集调度" name="schedule">
          <el-form-item label="采集模式" prop="schedule.mode">
            <el-radio-group v-model="formData.schedule.mode">
              <el-radio label="once">一次性采集</el-radio>
              <el-radio label="scheduled">定时采集</el-radio>
              <el-radio label="watch">文件监视</el-radio>
            </el-radio-group>
          </el-form-item>

          <template v-if="formData.schedule.mode === 'scheduled'">
            <el-form-item label="采集频率" prop="schedule.cron">
              <el-select
                v-model="formData.schedule.cron"
                placeholder="请选择采集频率"
                style="width: 100%"
              >
                <el-option label="每小时" value="0 0 * * * ?" />
                <el-option label="每天" value="0 0 0 * * ?" />
                <el-option label="每周" value="0 0 0 ? * MON" />
                <el-option label="每月" value="0 0 0 1 * ?" />
                <el-option label="自定义" value="custom" />
              </el-select>
            </el-form-item>

            <template v-if="formData.schedule.cron === 'custom'">
              <el-form-item label="CRON表达式" prop="schedule.customCron">
                <el-input
                  v-model="formData.schedule.customCron"
                  placeholder="请输入CRON表达式"
                />
                <span class="el-form-item__tip">例如: 0 0/30 * * * ? 表示每30分钟执行一次</span>
              </el-form-item>
            </template>
          </template>

          <template v-else-if="formData.schedule.mode === 'watch'">
            <el-form-item label="监视间隔(秒)" prop="schedule.watchInterval">
              <el-input-number
                v-model="formData.schedule.watchInterval"
                :min="10"
                :max="3600"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="文件匹配模式" prop="schedule.filePattern">
              <el-input
                v-model="formData.schedule.filePattern"
                placeholder="例如: data_*.xlsx"
              />
              <span class="el-form-item__tip">支持通配符 * 和 ?</span>
            </el-form-item>
          </template>

          <el-form-item label="增量采集" prop="schedule.incremental">
            <el-switch v-model="formData.schedule.incremental" />
          </el-form-item>

          <template v-if="formData.schedule.incremental">
            <el-form-item label="增量标识字段" prop="schedule.incrementalField">
              <el-input
                v-model="formData.schedule.incrementalField"
                placeholder="例如: update_time"
              />
            </el-form-item>

            <el-form-item label="上次采集值" prop="schedule.lastIncrementalValue">
              <el-input
                v-model="formData.schedule.lastIncrementalValue"
                placeholder="例如: 2023-01-01"
                :disabled="true"
              />
            </el-form-item>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
        <el-button type="success" @click="previewExcel">预览</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'EditExcelDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'submit', 'preview'],
  setup(props, { emit }) {
    const visible = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val)
    })

    const title = computed(() => 
      props.editData ? '编辑Excel采集配置' : '新增Excel采集配置'
    )

    const activeTab = ref('basic')
    const formRef = ref(null)
    const fileList = ref([])
    const previewData = ref([])
    const previewColumns = ref([])
    const sheetList = ref([])

    // 默认表单数据
    const defaultFormData = {
      id: '',
      name: '',
      description: '',
      status: 1,
      fileConfig: {
        sourceType: 'upload',
        uploadFile: null,
        filePath: '',
        ftp: {
          host: '',
          port: 21,
          username: '',
          password: '',
          filePath: ''
        }
      },
      sheetConfig: {
        sheetName: '',
        startRow: 1,
        headerRow: 1,
        columnMappings: [],
        filterCondition: ''
      },
      schedule: {
        mode: 'once',
        cron: '0 0 * * * ?',
        customCron: '',
        watchInterval: 60,
        filePattern: '*.xlsx',
        incremental: false,
        incrementalField: '',
        lastIncrementalValue: ''
      }
    }

    const formData = ref(JSON.parse(JSON.stringify(defaultFormData)))

    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入数据源名称', trigger: 'blur' },
        { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
      ],
      'fileConfig.uploadFile': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.fileConfig.sourceType === 'upload' && !value) {
              return callback(new Error('请上传Excel文件'))
            }
            callback()
          },
          trigger: 'change'
        }
      ],
      'fileConfig.filePath': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.fileConfig.sourceType === 'path' && !value) {
              return callback(new Error('请输入文件路径'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ],
      'fileConfig.ftp.host': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.fileConfig.sourceType === 'ftp' && !value) {
              return callback(new Error('请输入FTP服务器地址'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ],
      'sheetConfig.sheetName': [
        { required: true, message: '请选择工作表', trigger: 'change' }
      ],
      'sheetConfig.columnMappings': [
        { 
          validator: (rule, value, callback) => {
            if (value.length === 0) {
              return callback(new Error('至少需要配置一个列映射'))
            }
            const hasEmpty = value.some(item => !item.excelColumn || !item.targetField)
            if (hasEmpty) {
              callback(new Error('列名和目标字段不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      ],
      'schedule.customCron': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.schedule.mode === 'scheduled' && 
                formData.value.schedule.cron === 'custom' && 
                !value) {
              return callback(new Error('请输入CRON表达式'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ]
    }

    // 上传URL（实际项目中应该是后端接口）
    const uploadUrl = ref('/api/file/upload')

    // 上传前检查
    const beforeUpload = (file) => {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                     file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        ElMessage.error('只能上传Excel文件!')
        return false
      }
      return true
    }

    // 上传成功处理
    const handleUploadSuccess = (response, file) => {
      formData.value.fileConfig.uploadFile = response.data
      fileList.value = [file]
      ElMessage.success('上传成功')
    }

    // 处理文件来源类型变化
    const handleSourceTypeChange = (type) => {
      // 重置相关字段
      if (type !== 'upload') {
        formData.value.fileConfig.uploadFile = null
        fileList.value = []
      }
      if (type !== 'path') {
        formData.value.fileConfig.filePath = ''
      }
      if (type !== 'ftp') {
        formData.value.fileConfig.ftp = JSON.parse(JSON.stringify(defaultFormData.fileConfig.ftp))
      }
    }

    // 浏览服务器路径
    const browseServerPath = () => {
      // 这里应该调用API打开服务器文件浏览器
      ElMessage.info('打开服务器文件浏览器')
    }

    // 处理工作表变化
    const handleSheetChange = (sheetName) => {
      // 这里应该根据选择的工作表获取列信息
      // 模拟获取列信息
      if (sheetName) {
        const mockColumns = ['A', 'B', 'C', 'D']
        previewColumns.value = mockColumns
        formData.value.sheetConfig.columnMappings = mockColumns.map(col => ({
          excelColumn: col,
          targetField: col.toLowerCase(),
          dataType: 'string'
        }))
      }
    }

    // 自动映射列
    const autoMapColumns = () => {
      if (previewColumns.value.length > 0) {
        formData.value.sheetConfig.columnMappings = previewColumns.value.map(col => ({
          excelColumn: col,
          targetField: col.toLowerCase().replace(/\s+/g, '_'),
          dataType: 'string'
        }))
      } else {
        ElMessage.warning('请先选择工作表并预览数据')
      }
    }

    // 删除列映射
    const removeColumnMapping = (index) => {
      formData.value.sheetConfig.columnMappings.splice(index, 1)
    }

    // 预览Excel数据
    const previewExcel = () => {
      // 这里应该调用API预览Excel数据
      if (!formData.value.sheetConfig.sheetName) {
        ElMessage.warning('请先选择工作表')
        return
      }

      // 模拟预览数据
      const mockData = []
      for (let i = 0; i < 5; i++) {
        const row = {}
        previewColumns.value.forEach(col => {
          row[col] = `${col}_数据${i + 1}`
        })
        mockData.push(row)
      }
      previewData.value = mockData
      ElMessage.success('预览数据加载成功')
    }

    // 对话框关闭
    const handleClosed = () => {
      formRef.value?.resetFields()
      formData.value = JSON.parse(JSON.stringify(defaultFormData))
      fileList.value = []
      previewData.value = []
      previewColumns.value = []
      sheetList.value = []
    }

    // 提交表单
    const submitForm = async () => {
      try {
        await formRef.value.validate()
        
        // 处理自定义CRON表达式
        const finalData = JSON.parse(JSON.stringify(formData.value))
        if (finalData.schedule.cron === 'custom') {
          finalData.schedule.cron = finalData.schedule.customCron
        }
        delete finalData.schedule.customCron
        
        emit('submit', finalData)
        visible.value = false
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('请检查表单填写是否正确')
      }
    }

    // 监听编辑数据变化
    watch(() => props.editData, (newVal) => {
      if (newVal) {
        formData.value = JSON.parse(JSON.stringify({
          ...defaultFormData,
          ...newVal,
          fileConfig: {
            ...defaultFormData.fileConfig,
            ...(newVal.fileConfig || {}),
            ftp: {
              ...defaultFormData.fileConfig.ftp,
              ...(newVal.fileConfig?.ftp || {})
            }
          },
          sheetConfig: {
            ...defaultFormData.sheetConfig,
            ...(newVal.sheetConfig || {})
          },
          schedule: {
            ...defaultFormData.schedule,
            ...(newVal.schedule || {})
          }
        }))
        
        // 处理自定义CRON表达式
        if (newVal.schedule?.cron && 
            !['0 0 * * * ?', '0 0 0 * * ?', '0 0 0 ? * MON', '0 0 0 1 * ?'].includes(newVal.schedule.cron)) {
          formData.value.schedule.cron = 'custom'
          formData.value.schedule.customCron = newVal.schedule.cron
        }
        
        // 初始化工作表列表和预览数据
        if (newVal.sheetConfig?.sheetName) {
          sheetList.value = [newVal.sheetConfig.sheetName]
          handleSheetChange(newVal.sheetConfig.sheetName)
        }
      }
    }, { immediate: true })

    return {
      visible,
      title,
      activeTab,
      formRef,
      formData,
      formRules,
      fileList,
      previewData,
      previewColumns,
      sheetList,
      uploadUrl,
      beforeUpload,
      handleUploadSuccess,
      handleSourceTypeChange,
      browseServerPath,
      handleSheetChange,
      autoMapColumns,
      removeColumnMapping,
      previewExcel,
      handleClosed,
      submitForm
    }
  }
}
</script>

<style scoped>
.el-form-item__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  display: inline-block;
}

.upload-demo {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>